package com.vnt;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;

import java.io.*;
import org.kalmeo.kuix.core.model.DataProvider;

import com.ilove.core.*;
public class Pad extends DataProvider {

	public static String tmp_code;
	private String title;
	private String content;
	private String img;
	public static int page=1;

	String ScheUrl = "http://117.6.131.167/AppServlet/servlet/Schedules?";
	String lotUrl = "http://117.6.131.167/AppServlet/servlet/Lottery?";
	String vasUrl = "http://117.6.131.167/AppServlet/servlet/SubIndex?";
	String cateUrl = "http://117.6.131.167/AppServlet/servlet/Category?cateCode=";
	String contentlisturl = "http://117.6.131.167/AppServlet/servlet/ContentList?cateCode=";
	String contenturl = "http://117.6.131.167/AppServlet/servlet/Content?id=";
	// String baseUrl = "http://117.6.131.167/AppServlet/servlet/MeoVat?";
	// String memberUrl =
	// "http://117.6.131.167/AppServlet/servlet/MemberActive?ver=0&uid="; // 0
	// spam , 1 mstore
	
	
	// Property names
	private static final String INDEX_LISTS_PROPERTY = "indexLists";
	private static final String SUB_INDEX_LISTS_PROPERTY = "subIndexLists";
	private static final String CONTENT_INDEX_LISTS_PROPERTY = "contentIndexLists";
	private static final String TITLE_PROPERTY = "title";
	private static final String CONTENT_PROPERTY = "content";

	public void setImg(String img) {
		this.img = img;
		dispatchUpdateEvent("img");
	}

	public void setTitle(String title) {
		this.title = title;
		dispatchUpdateEvent(TITLE_PROPERTY);
	}

	public void setContent(String content) {
		this.content = content;
		dispatchUpdateEvent(CONTENT_PROPERTY);
	}

	// override the parent method to handle user defined value
	protected Object getUserDefinedValue(String property) {

		if (TITLE_PROPERTY.equals(property)) {
			return this.title;
		}

		if (CONTENT_PROPERTY.equals(property)) {
			return this.content;
		}

		if ("img".equals(property)) {
			return this.img;
		}

		// default behavior if the property has not been found
		return null;
	}

	protected boolean isActived() throws Exception {
		// ILOVE.KeyActive = RMSManager.readUID();
		// System.out.println("Start isActived");
		// String url = memberUrl + ILOVE.KeyActive;
		// System.out.println(url);
		// String sMember = getData(url);
		// if (sMember.startsWith("Active")) {
		// String UID = sMember.substring(10, sMember.length());
		// System.out.println("Active :" + UID);
		// RMSManager.saveUID(UID);
		// ILOVE.KeyActive = sMember;
		// Kuix.alert("Bạn cần kích hoạt gia hạn để tiếp tục
		// sử dụng ứng dụng. Bạn có đồng ý không? (Bạn có
		// thể sử dụng khi nhận được tin nhắn xác nhận kích
		// hoạt thành công)",
		// KuixConstants.ALERT_QUESTION
		// | KuixConstants.ALERT_YES
		// | KuixConstants.ALERT_NO, "sendsms",
		// "!exit");
		// } else {
		// System.out.println("UID :" + sMember);
		// RMSManager.saveUID(sMember);
		//
		// }
		return false;
	}

	public void getIndexList(String cateCode, int database) throws Exception {
		ILOVEContants.INDEX_LIST = null;
		// Get content from server
		// id = 1 load data from media id = 0 load from vas
		String url = "";
		if (database == 0) {
			url = vasUrl + "parentid=" + cateCode;
		} else if(database == 4){	
			url = lotUrl;
		} else if(database == 5){	
			url = ScheUrl;
		}else {
			url = cateUrl + cateCode;
		}
		System.out.println("url "+url);
		if (ILOVEContants.INDEX_LIST == null) {
			// Get content and split to Array
			String sTopic = getData(url);
			if (!"null".equalsIgnoreCase(sTopic) || !"".equalsIgnoreCase(sTopic.trim()))
				ILOVEContants.INDEX_LIST = split(sTopic, "\n");
		}
		removeAllItems(INDEX_LISTS_PROPERTY);

		for (int i = 0; i < ILOVEContants.INDEX_LIST.length - 1; i++) {
			int id = 0;
			String code = "";
			String name = "";
			String data = ILOVEContants.INDEX_LIST[i];
			System.out.println("data "+data);
			id = i + 1;
			if(database==5){
				code = data.substring(0, data.indexOf("@@@")-8);
				System.out.println("code "+code);
				name = "LTH ngày "+data.substring(0, data.indexOf("@@@"));
				System.out.println("name "+name);
			}
			else{
				code = data.substring(0, data.indexOf("@@@"));
				name = data.substring(data.indexOf("@@@") + 3, data.length() - 1);
			}
			IndexList indexList = new IndexList();
			indexList.id = id;
			indexList.code = code;
			indexList.name = name;
			addItem(INDEX_LISTS_PROPERTY, indexList);
		}

	}

	public String[] getGroupContent(String code, int database, String name) throws Exception {
		String url = "";
		ILOVEContants.SUB_INDEX_LIST = null;
		System.out.println("name now is "+name+database+code);
		if (database != 0 && database!=4 && database!=5)
			url = cateUrl + code;
		//Lottery
		else if(database == 4){	
				url = lotUrl + "reg=" + code;
		}
		//Schedules
		else if(database==5){
			url = ScheUrl + "date=" + code;
		}
		//Meo Vat & Doc Truyen
		else if(database==0){
			url = vasUrl + "parentid=" + code;
		}
		System.out.println("getGroupContent" + url);
		String sGroup = getData(url);
		
		if(database==0 && (sGroup.equals(null) || sGroup.equals(""))){
			url = vasUrl + "groupId=" + code + "&page=" + page;
			SubIndexFrame.getListPage = true;
			tmp_code = code;
			sGroup = getData(url);
			if(sGroup.equals(null) || sGroup.equals("")){
				url = vasUrl + "groupId=" + code + "&page=" + (page-1);
				sGroup = getData(url);
				if(sGroup.equals(null) || sGroup.equals(""))
					return null;
			}
		}
		String[] subIndex = split(sGroup, "\n");
		ILOVEContants.SUB_INDEX_LIST = subIndex;
		return subIndex;
	}

	public void getSubIndex(String[] subIndex, String groupName)
			throws Exception {
		removeAllItems(SUB_INDEX_LISTS_PROPERTY);
		setTitle(groupName);
		for (int i = 0; i < subIndex.length - 1; i++) {
			int id = 0;
			String code = "";
			String name = "";
			String data = subIndex[i];
			System.out.println(data);
			id = i + 1;
			code = data.substring(0, data.indexOf("@@@"));
			name = data.substring(data.indexOf("@@@") + 3, data.length());
			SubIndexList subIndexList = new SubIndexList();
			subIndexList.id = id;									System.out.println("subIndexList.id"+id);
			subIndexList.code = code;								System.out.println("subIndexList.code"+subIndexList.code);
			subIndexList.name = name;								System.out.println("subIndexList.name"+subIndexList.name);
			addItem(SUB_INDEX_LISTS_PROPERTY, subIndexList);
			}
	}

	public void getContentIndex(String[] contentIndex, String groupName)
			throws Exception {
		removeAllItems(SUB_INDEX_LISTS_PROPERTY);
		setTitle(groupName);
		for (int i = 0; i < contentIndex.length - 1; i++) {
			String data = contentIndex[i];
			if(groupName == "XOSO"){
				String date = data.substring(0,data.indexOf("@@@"));
				System.out.println(date);
				SubIndexList list = new SubIndexList();
				list.name = date;
				addItem(SUB_INDEX_LISTS_PROPERTY, list);
			}
			else if(groupName == "Truyen"){
				String id = data.substring(0,data.indexOf("@@@"));
				String title = data.substring(data.indexOf("@@@")+3,data.length());
				System.out.println(id);
				System.out.println(title);
				SubIndexList list = new SubIndexList();
				list.id = Integer.parseInt(id);
				list.name = title;
				addItem(SUB_INDEX_LISTS_PROPERTY, list);
			}
			else{
			String[] content = split(contentIndex[i],"@@@");
			
			ContentList list = new ContentList();
			list.name = content[0];
			list.data = content[1];
			list.img = content[2];
			String urlimage = "http://210.211.99.58:6868/Upload"+ content[2];
			System.out.println(urlimage.trim()+" "+list.name);
			Image imgav = getImage(urlimage.trim());
			list.avatar = imgav ;
			addItem(CONTENT_INDEX_LISTS_PROPERTY, list);
			}
		}
	}

	public String[] getContentList(String catecode, int type, String name) throws Exception {
		// Get content from server and split into array
		String url = null;
		if(type==4)
			url = lotUrl + "lottery_brand_id=" + catecode;
		else if(name=="Truyen"){
			url = vasUrl + "parentid=" + catecode;
			String sContent = getData(url);
			if ("null".equalsIgnoreCase(sContent)
					|| "".equalsIgnoreCase(sContent.trim())){
				url = vasUrl + "groupId=" + catecode;
			}
		}
		else
			url = contentlisturl + catecode + "&type=" + type;
		System.out.println("getContentList " + url);
		String sContent = getData(url);
		if ("null".equalsIgnoreCase(sContent)
				|| "".equalsIgnoreCase(sContent.trim()))
			return null;
		String[] subIndex = split(sContent, "\n");
		ILOVEContants.SUB_INDEX_LIST = subIndex;
		return subIndex;
	}

	public ContentList getContentData(String contentid, int type, String name)
			throws Exception {
		// Get content from server and split into array
		String url = "";
		if (type != 0 && type != 4 && type != 5)
			url = contenturl + contentid + "&type=" + type;
		else if(type == 4 && name != "SOI" && name != "CAU")
			url = lotUrl + "lottery_brand_id=" + contentid + "&date=" + name; 
		else if(type == 4 && name == "SOI")
			url = lotUrl + "soi=1"; 
		else if(type == 4 && name == "CAU")
			url = lotUrl + "soi=1"; 
		else if(type == 5){
			url = ScheUrl + "scheduleId=" + contentid;
			//make hour_text bold
//			String sContent = getData(url);
//			// Split sContent and make hour string bold
//			String hour = "";
//			String tmp_content = "";
//			String[] tmp = split(sContent, "\n");
//			for(int i=0; i<tmp.length; i++){
//				System.out.println("tmp"+i+" "+tmp[i]);
//				}
//			sContent = "";
//			for(int i=0;i<tmp.length-2;i++){
//				hour = "<b>"+tmp[i].substring(0, 5)+"</b>";
//				System.out.println(hour);
//				tmp_content = tmp[i].substring(6, tmp[i].length())+"<br />";
//				System.out.println(tmp_content);
//				sContent += hour + tmp_content;
//			}
//			System.out.println(sContent);
//			ContentList list = new ContentList();
//			list.data = sContent;
//			return list;
		}
		else
			url = vasUrl + "contentId=" + contentid;

		System.out.println("getContentData" + url);
		String sContent = getData(url);
		if(type==4 && name == "SOI" || name == "CAU"){
		StringBuffer str = new StringBuffer(sContent);
		str.setCharAt(sContent.indexOf("<MaTinh>"),'(');
		str.setCharAt(sContent.indexOf("<MaTinh>")+7,')');
		sContent = str.toString();
		}
		String[] content = null;
		if ("null".equalsIgnoreCase(sContent)
				|| "".equalsIgnoreCase(sContent.trim()))
			return null;
		else
			content = split(sContent, "@@@");
		
		ContentList list = new ContentList();
		if(type==4 || type==5){
		list.data = content[0];
		}
		else{
		list.name = content[0];
		list.data = content[1];
		list.name = content[2];
		}
		return list;

	}
	public static String getData(String serverUrl) throws IOException {
		HttpConnection connection = null;
		InputStream inputstream = null;
		String str = null;
		int actual = 0;
		try {
			connection = (HttpConnection) Connector.open(serverUrl);
			// HTTP Request
			connection.setRequestMethod(HttpConnection.GET);
			// connection.setRequestProperty("Content-Type", "//text plain");
			connection.setRequestProperty("Connection", "close");
			// HTTP Response
			System.out.println("Status Line Code: "
					+ connection.getResponseCode());
			System.out.println("Status Line Message: "
					+ connection.getResponseMessage());
			if (connection.getResponseCode() == HttpConnection.HTTP_OK) {
				System.out.println(connection.getHeaderField(0) + " "
						+ connection.getHeaderFieldKey(0));
				System.out.println("Header Field Date: "
						+ connection.getHeaderField("date"));

				inputstream = connection.openInputStream();
				int length = (int) connection.getLength();
				if (length != -1) {
					byte[] incomingData = new byte[length];
					// inputstream.read(incomingData);
					actual = inputstream.read(incomingData);
					str = new String(incomingData, 0, actual, "UTF-8");
				} else {
					ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
					int ch;
					while ((ch = inputstream.read()) != -1) {
						bytestream.write(ch);
					}
					str = new String(bytestream.toByteArray(), 0, bytestream
							.size(), "UTF-8");
					bytestream.close();
				}
				System.out.println(str);
			}
		} catch (IOException error) {
			System.out.println("Caught IOException: " + error.toString());
		} finally {
			if (inputstream != null) {
				try {
					inputstream.close();
				} catch (Exception error) {
					/* log error */
				}
			}
			if (connection != null) {
				try {
					connection.close();
				} catch (Exception error) {
					/* log error */
				}
			}
		}
		return str;
	}

	/*--------------------------------------------------
	 * Open connection and download png into a byte array.
	 *-------------------------------------------------*/
	public static Image getImage(String url) throws IOException {
		System.out.println(url);
		HttpConnection connection = (HttpConnection) Connector.open(url,
				Connector.READ);
		connection.setRequestMethod(HttpConnection.GET);
		DataInputStream iStrm = connection.openDataInputStream();
		ByteArrayOutputStream bStrm = null;
		Image im = null;

		try {
			// ContentConnection includes a length method
			byte imageData[];
			int length = (int) connection.getLength();
			if (length != -1) {
				imageData = new byte[length];
				// Read the png into an array
				iStrm.readFully(imageData);
			} else // Length not available...
			{
				bStrm = new ByteArrayOutputStream();
				int ch;
				while ((ch = iStrm.read()) != -1)
					bStrm.write(ch);
				imageData = bStrm.toByteArray();
				bStrm.close();
			}
			// Create the image from the byte array
			im = Image.createImage(imageData, 0, imageData.length);
		} finally {
			// Clean up
			if (iStrm != null)
				iStrm.close();
			if (connection != null)
				connection.close();
			if (bStrm != null)
				bStrm.close();
		}
		return (im == null ? null : im);
	}

	public String[] split(String original, String separator) {
		Vector nodes = new Vector();
		// Parse nodes into vector
		int index = original.indexOf(separator);
		while (index >= 0) {
			nodes.addElement(original.substring(0, index));
			original = original.substring(index + separator.length());
			index = original.indexOf(separator);
		}
		// Get the last node
		nodes.addElement(original);
		// Create split string array
		String[] result = new String[nodes.size()];
		if (nodes.size() > 0) {
			for (int loop = 0; loop < nodes.size(); loop++) {
				result[loop] = (String) nodes.elementAt(loop);
			}
		}
		return result;
	}

	public static String replaceOld(final String aInput,
			final String aOldPattern, final String aNewPattern) {
		if (aOldPattern.equals("")) {
			throw new IllegalArgumentException("Old pattern must have content.");
		}

		final StringBuffer result = new StringBuffer();
		int startIdx = 0;
		int idxOld = 0;
		while ((idxOld = aInput.indexOf(aOldPattern, startIdx)) >= 0) {
			result.append(aInput.substring(startIdx, idxOld));
			result.append(aNewPattern);
			startIdx = idxOld + aOldPattern.length();
		}
		result.append(aInput.substring(startIdx));
		return result.toString();
	}

	public String proccessData(String[] arrString, int length) {
		String arr = "";
		int count = 0;
		for (int i = 0; i < arrString.length; i++) {
			count += arrString[i].length();
			if (count < length) {
				arr = arr + "<br />";
			} else {
				arr = arr + "@@@";
				count = 0;
			}
			arr = arr + arrString[i];
		}
		return arr;
	}

}